<template>
  <view class="register-container">
    <view class="logo">
      <text class="logo-text">荷叶健康</text>
    </view>
    
    <view class="register-form">
      <!-- 头像上传组件 -->
      <view class="avatar-upload" @tap="uploadImage">
        <image v-if="avatarUrl" :src="avatarUrl" class="avatar"></image>
        <view v-else class="avatar-placeholder">上传头像</view>
      </view>

      <view class="input-group">
        <input type="text" v-model="nickname" placeholder="请输入用户昵称" />
      </view>
      
      <view class="input-group phone-group">
        <input type="text" v-model="phone" placeholder="请输入手机号" maxlength="11" />
      </view>
      
      <view class="input-group code-group">
        <input type="text" v-model="code" placeholder="请输入验证码" maxlength="6" />
        <button 
          class="code-btn" 
          :disabled="codeBtnDisabled"
          @tap="sendCode"
        >{{ codeBtnText }}</button>
      </view>
      
      <button class="register-btn" @tap="handleRegister">注册</button>
      
      <view class="login-link">
        <text @tap="goToLogin">已有账号？立即登录</text>
      </view>
    </view>
  </view>
</template>

<script>
import { userApi } from '@/api/user'

export default {
  data() {
    return {
      nickname: '',
      phone: '',
      code: '',
      avatarUrl: '',
      loading: false,
      codeBtnDisabled: false,
      codeBtnText: '获取验证码',
      timer: null,
      countdown: 60
    }
  },
  methods: {
    async handleRegister() {
      // 表单验证
      if (!this.nickname || !this.phone || !this.code || !this.avatarUrl) {
        uni.showToast({
          title: '请填写完整信息',
          icon: 'none'
        })
        return
      }

      if (this.phone.length !== 11) {
        uni.showToast({
          title: '请输入正确的手机号',
          icon: 'none'
        })
        return
      }

      if (this.code.length !== 4) {
        uni.showToast({
          title: '请输入4位验证码',
          icon: 'none'
        })
        return
      }

      if (this.loading) return
      this.loading = true

      try {
        const res = await userApi.register({
          nickname: this.nickname,
          phone: this.phone,
          code: this.code,
          avatarUrl: this.avatarUrl
        })

        if (res.code === 200) {
          uni.showToast({
            title: '注册成功',
            icon: 'success'
          })

          // 注册成功后延迟跳转到登录页
          setTimeout(() => {
            uni.navigateBack()
          }, 1500)
        } else {
          throw new Error(res.errorMessage || '注册失败')
        }
      } catch (error) {
        uni.showToast({
          title: error.message || '注册失败',
          icon: 'none'
        })
      } finally {
        this.loading = false
      }
    },

    async sendCode() {
      if (this.codeBtnDisabled) return
      
      if (!this.phone || this.phone.length !== 11) {
        uni.showToast({
          title: '请输入正确的手机号',
          icon: 'none'
        })
        return
      }

      try {
        const res = await userApi.sendCode(this.phone)
        if (res.code === 200) {
          this.startCountdown()
          uni.showToast({
            title: '验证码已发送',
            icon: 'success'
          })
        } else {
          throw new Error(res.errorMessage || '发送失败')
        }
      } catch (error) {
        uni.showToast({
          title: error.message || '发送失败',
          icon: 'none'
        })
      }
    },

    startCountdown() {
      this.codeBtnDisabled = true
      this.countdown = 60
      this.codeBtnText = `${this.countdown}s后重新获取`
      
      this.timer = setInterval(() => {
        if (this.countdown > 0) {
          this.countdown--
          this.codeBtnText = `${this.countdown}s后重新获取`
        } else {
          this.stopCountdown()
        }
      }, 1000)
    },

    stopCountdown() {
      if (this.timer) {
        clearInterval(this.timer)
        this.timer = null
      }
      this.codeBtnDisabled = false
      this.codeBtnText = '获取验证码'
    },

    // 封装的图片上传方法
    async uploadImage() {
      try {
        const res = await new Promise((resolve, reject) => {
          uni.chooseImage({
            count: 1,
            sizeType: ['compressed'],
            sourceType: ['album', 'camera'],
            success: resolve,
            fail: reject
          })
        })
        
        if (res.tempFilePaths && res.tempFilePaths.length > 0) {
          uni.showLoading({
            title: '上传中...'
          })
          
          // 上传图片并获取返回的URL
          const imageUrl = await userApi.uploadAvatar(res.tempFilePaths[0])
          
          // 设置头像URL用于回显和表单提交
          this.avatarUrl = imageUrl
          
          uni.showToast({
            title: '上传成功',
            icon: 'success'
          })
        }
      } catch (error) {
        console.error('上传错误:', error)
        uni.showToast({
          title: error.message || '上传失败',
          icon: 'none'
        })
      } finally {
        uni.hideLoading()
      }
    },

    goToLogin() {
      uni.navigateBack()
    }
  },

  beforeDestroy() {
    // 组件销毁前清除定时器
    this.stopCountdown()
  }
}
</script>

<style lang="scss">
.register-container {
  padding: 60rpx 40rpx;
  
  .logo {
    text-align: center;
    margin-bottom: 60rpx;
    
    .logo-text {
      font-size: 48rpx;
      font-weight: bold;
      color: #007AFF;
    }
  }
  
  .register-form {
    .avatar-upload {
      margin-bottom: 40rpx;
      display: flex;
      justify-content: center;
      
      .avatar {
        width: 150rpx;
        height: 150rpx;
        border-radius: 50%;
        border: 2rpx solid #ddd;
      }
      
      .avatar-placeholder {
        width: 150rpx;
        height: 150rpx;
        border-radius: 50%;
        background: #f5f5f5;
        display: flex;
        align-items: center;
        justify-content: center;
        color: #666;
        font-size: 28rpx;
      }
    }

    .input-group {
      background: #f5f5f5;
      border-radius: 8rpx;
      padding: 20rpx 30rpx;
      margin-bottom: 30rpx;
      
      input {
        height: 80rpx;
        font-size: 28rpx;
      }

      &.code-group {
        display: flex;
        align-items: center;
        
        input {
          flex: 1;
          margin-right: 20rpx;
        }
        
        .code-btn {
          width: 200rpx;
          height: 80rpx;
          line-height: 80rpx;
          font-size: 26rpx;
          color: #007AFF;
          background: none;
          padding: 0;
          
          &[disabled] {
            color: #999;
          }
        }
      }
    }
    
    .register-btn {
      background: #007AFF;
      color: #fff;
      height: 88rpx;
      line-height: 88rpx;
      border-radius: 44rpx;
      margin: 60rpx 0;
    }
    
    .login-link {
      text-align: center;
      
      text {
        color: #007AFF;
        font-size: 28rpx;
      }
    }
  }
}
</style>